/*
 * iShopPlace Project.
 */
package ishopplace.view.bean;

import ishopplace.model.businessobject.Cart;
import ishopplace.model.businessobject.CartItem;
import ishopplace.model.businessobject.Item;
import ishopplace.model.exception.iShopPlaceException;
import ishopplace.view.util.FacesUtils;

import java.util.List;
import java.util.Iterator;


/**
 * Shopping cart backing bean.
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class CartBean extends BaseBean {
	private static final String ITEM_ID_PARAMETER_NAME = "itemId";
	private Cart cart;
	
	public CartBean() {
		super();
		this.cart = new Cart();
		this.logger.debug("CartBean is created");
	}
	
	/**
	 * Backing bean action to add a new item to the cart.
	 * 
	 * @return the navigation result
	 */
	public String addItemAction() {
		this.logger.debug("addItemAction is invoked");
		String itemId = FacesUtils.getRequestParameter(ITEM_ID_PARAMETER_NAME);
		this.logger.debug("itemId = " + itemId);
		
		try {
			Item item = this.getServiceLocator().getCatalogService().getItem(itemId);
			this.cart.addItem(item);
		} catch(iShopPlaceException me) {
			String msg = "Could not add item to cart ";
			this.logger.error(msg, me);
			FacesUtils.addErrorMessage(msg + ": Internal Error");
			return NavigationResults.FAILURE;
		}
		this.logger.debug("Item is added to the cart successfully");
		return NavigationResults.SUCCESS;
	}
	
	/**
	 * Backing bean action to remove an item from the cart.
	 * 
	 * @return the navigation result
	 */
	public String removeItemAction() {
		this.logger.debug("removeItemAction is invoked");
		String itemId = FacesUtils.getRequestParameter(ITEM_ID_PARAMETER_NAME);
		this.logger.debug("itemId = " + itemId);
		
		this.cart.removeItemById(itemId);
		this.logger.debug("Item is removed from the cart successfully");
		return NavigationResults.SUCCESS;
	}
	
	/**
	 * Backing bean action to update the cart.
	 * 
	 * @return the navigation result
	 */
	public String updateAction() {
		this.logger.debug("updateAction is invoked");
		Iterator cartItems = this.cart.getCartItemList().iterator();
		while (cartItems.hasNext()) {
		  	CartItem cartItem = (CartItem)cartItems.next();
		  	
		  	if (cartItem.getQuantity() < 1) {
		  		cartItems.remove();
		  	}
		}
		this.logger.debug("Cart is updated successfully");
		return NavigationResults.SUCCESS;		
	}
	
	public Cart getCart() {
		return this.cart;
	}
	
	public int getNumberOfItems() {
		return this.cart.getCartItemList().size();
	}
	
	public List getCartItemList() {
		return this.cart.getCartItemList();
	}
}
